
/* -----------------
* brief 
* 1. this is code gen by tools 
* 2. for add/update/delete/query the data save in sql database   
*/

package appmanager

import (
	"errors"
	"github.com/go-xorm/xorm"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	"saas_sys_base/redishelper"

	//"github.com/mjiulee/lego/utils"
)


const REDIS_APP_ATTR_BY_ID_PREFIX string = "app_attr_by_id:"
const REDIS_APP_ATTR_BY_MINI_APP_ID_PREFIX string = "app_attr_by_mini_app_id:"


func (t *AppAttr) CacheUpdateAllBy(item *AppAttr) {
	if item.Id <= 0 {
		lego.LogError(errors.New("item.Id <= 0 in CacheUpdateAllBy"))
		return
	}
	_ = redishelper.RedisSetKeyEx(REDIS_APP_ATTR_BY_ID_PREFIX+utils.Int64ToString(item.Id), item)
	_ = redishelper.RedisSetKeyEx(REDIS_APP_ATTR_BY_MINI_APP_ID_PREFIX+utils.Int64ToString(item.MiniAppId), item)
}

func (t *AppAttr) CacheDelAllBy(item *AppAttr) {
	if item.Id <= 0 {
		lego.LogError(errors.New("item.Id <= 0 in CacheDelAllBy"))
		return
	}
	_ = redishelper.RedisDelKey(REDIS_APP_ATTR_BY_ID_PREFIX+utils.Int64ToString(item.Id))
	_ = redishelper.RedisDelKey(REDIS_APP_ATTR_BY_MINI_APP_ID_PREFIX+utils.Int64ToString(item.MiniAppId))
}

/* 根据id获取记录
 * -----------------
 */
func (t *AppAttr) RecodeById(id int64) *AppAttr {
	item := new(AppAttr)
	err := redishelper.RedisGetKeyEx(REDIS_APP_ATTR_BY_ID_PREFIX+utils.Int64ToString(id), item)
	if err == nil {
		return item
	}

	_, err = lego.GetDBEngine().ID(id).Where("if_del = ?", 0).Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}

	t.CacheUpdateAllBy(item)
	return item
}

func (t *AppAttr) RecodeByMiniAppId(mini_app_id int64) *AppAttr {
	item := new(AppAttr)
	err := redishelper.RedisGetKeyEx(REDIS_APP_ATTR_BY_MINI_APP_ID_PREFIX+utils.Int64ToString(mini_app_id), item)
	if err == nil {
		return item
	}
	_, err = lego.GetDBEngine().Where("if_del = ?", 0).And("mini_app_id = ?", mini_app_id).Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}

	t.CacheUpdateAllBy(item)

	return item
}

func (t *AppAttr) RecodeByMiniAppIdWithsession(session*xorm.Session, mini_app_id int64) *AppAttr {
	item := new(AppAttr)
	err := redishelper.RedisGetKeyEx(REDIS_APP_ATTR_BY_MINI_APP_ID_PREFIX+utils.Int64ToString(mini_app_id), item)
	if err == nil {
		return item
	}

	_, err = lego.GetDBEngine().Where("if_del = ?", 0).And("mini_app_id = ?", mini_app_id).Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}

	t.CacheUpdateAllBy(item)

	return item
}
/* 添加
 * -----------------
 */
func (t *AppAttr) AddRecode(item2add *AppAttr) bool {
	item2add.Id = lego.UUID()
	_, err := lego.GetDBEngine().Insert(item2add)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

func (t *AppAttr) AddRecodeWithsession(session*xorm.Session,item2add *AppAttr) bool {
	item2add.Id = lego.UUID()
	_, err := session.Insert(item2add)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 删除(硬删除)*/
func (t *AppAttr) DelRecodeById(id int64) bool {
	item := new(AppAttr)
	_, err := lego.GetDBEngine().ID(id).Delete(item)
	if err != nil {
        lego.LogError(err)
        return false
    }

	itemDel := new(AppAttr)
	_ = redishelper.RedisGetKeyEx(REDIS_APP_ATTR_BY_ID_PREFIX+utils.Int64ToString(id), itemDel)
	t.CacheDelAllBy(item)

    return true
}

func (t *AppAttr) DelRecodeByIdWithSession(session*xorm.Session,id int64) bool {
	item := new(AppAttr)
	_, err := session.ID(id).Delete(item)
	if err != nil {
        lego.LogError(err)
        return false
    }

	itemDel := new(AppAttr)
	_ = redishelper.RedisGetKeyEx(REDIS_APP_ATTR_BY_ID_PREFIX+utils.Int64ToString(id), itemDel)
	t.CacheDelAllBy(item)

    return true
}

/* 更新
 * -----------------*/
func (t *AppAttr) UpdateRecode(rc *AppAttr) bool {
	_, err := lego.GetDBEngine().Id(rc.Id).Update(rc)
	if err != nil {
        lego.LogError(err)
        return false
    }

	t.CacheDelAllBy(rc)

    return true
}

func (t *AppAttr) UpdateRecodeWithSession(session *xorm.Session,rc *AppAttr) bool {
	_, err := session.ID(rc.Id).Update(rc)
	if err != nil {
        lego.LogError(err)
        return false
    }

	t.CacheDelAllBy(rc)

    return true
}

func (t *AppAttr) AddOrUpdateRecodeByMiniAppId(rc *AppAttr, miniAppId int64) bool {

	session := lego.GetDBEngine().NewSession()
	defer session.Close()

	err := session.Begin()
	if err != nil {
		lego.LogError(err)
		return false
	}

	rcInDb := t.RecodeByMiniAppIdWithsession(session, miniAppId)
	if rcInDb == nil {
		isSuccess := t.AddRecodeWithsession(session, rc)
		if !isSuccess {
			err = session.Rollback()
			if err != nil {
				lego.LogError(err)
				return false

			}
			return true
		}

	} else {
		rc.Id = rcInDb.Id //注意不要漏了这里
		isSuccess := t.UpdateRecodeWithSession(session, rc)
		if !isSuccess {
			err = session.Rollback()
			if err != nil {
				lego.LogError(err)
				return false

			}
		}

	}

	err = session.Commit()
	if err != nil {
		lego.LogError(err)
		return false
	}

	return true
}


func (t *AppAttr) ListAppAttr(page,psize int) ([]AppAttr, int64, error) {
	start := (page*psize)
	resultList := make([]AppAttr, 0)

	session := lego.GetDBEngine().Table(AppAttr{}).Alias("t1").
		//Join("INNER", "tb_xx", "tb_xx.id = tb_xx.type_id").
		Where("if_del = ?", 0).
		Limit(psize, start).
		Asc("t1.mini_app_id")
		//Asc()
	//OrderBy("asc")

	session2 := *session.Clone()
	err := session.Find(&resultList)
	if err != nil {
		return nil, 0, err
	}

	total, err := session2.Count()
	if err != nil {
		return nil, 0, err
	}
	return resultList, total, err
}
